import React from 'react';
import { inject, observer } from 'mobx-react';
import { WeaLocaleProvider, WeaTable, WeaInputNumber, WeaCheckbox, WeaSearchGroup, WeaInput } from 'ecCom';
const toJS = mobx.toJS;
const getLabel = WeaLocaleProvider.getLabel;
@inject('planProgramViewStore')
@observer
export default class WorkSummary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { searchGroupVisible: true, searchGroupPreviewVisible: true,
      hasLoad:false,
      isShowCube:true,
    };
    this.store = this.props.planProgramViewStore;
    this.saveRef = ref => {
      this.refDom = ref;
    };
  }

  componentDidMount() {
    this.initCube()
  }
  //初始化建模
  initCube = () => {
    const cubeFiles = [
      `/spa/cube/static4engine/engine.js`,
      `/spa/cube/static4engine/engine.css`,
    ];
    const init = () => {
      this.setState((state, props) => ({ hasLoad: true }), () => {
        const { hasLoad } = this.state;
        if (hasLoad) {
          const { EcmeBaseStore, CubeModeStore, CubeCommonStore } = (window.weaCubeEngine && window.weaCubeEngine.store) || {};
          this.setState({
            EcmeBaseStore,
            CubeModeStore,
            CubeCommonStore
          })
        }
      });
    }
    loadjs.isDefined("bs_cube")
      ? loadjs.ready("bs_cube", init)
      : loadjs(cubeFiles, "bs_cube", init);
  }
  getPreviewColumns = () => {
    let fieldRows = this.store.fieldRows;
    let columns = [];
    let _this = this;

    let totalWidth = this.refDom ? this.refDom.clientWidth : 1000;
    let totalWidthCount = 0
    fieldRows.map(v => {
      if (v.isshow) {
        totalWidthCount += parseInt(v.showwidth)
      }
    })
    fieldRows.map((v, i) => {
      if (v.isshow == '1') {
        let title = v.customname ? v.customname : v.showname
        title = v.ismust == '1' ? `${title}(${getLabel(30036, '必填')})` : title
        columns.push({
          title,
          dataIndex: v.fieldname,
          key: v.fieldname,
          //   width:( parseInt(v.showwidth) / totalWidthCount) * totalWidth + 'px',
          width: v.showwidth + "%"
        });
      }
    });

    return columns;
  };

  getFieldNameColumn = (text, paramName) => {
    let { auth: { canedit, canview } } = this.store;
    let viewAttr = 2
    if (!canedit) {
      viewAttr = 1
    }
    return (
      <div>
        <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@4lvpxs`}
          viewAttr={viewAttr}
          onChange={e => {
            this.store.fieldRows.map((v, i) => {
              if (text == getLabel('25532', '是否必填') && v['isshow'] != '1') {
                return
              }
              //标题不能动 固定死
              if (v.fieldname != 'name') {
                v[paramName] = e;
              }
            });
          }}
        />{text}
      </div>
    );
  };
  checkBoxRender = (text, record, index, paramName) => {
    let viewAttr = 2;
    let { auth: { canedit, canview } } = this.store;
    if (
      record.fieldname == 'name' ||
      (paramName == 'ismust' && record.isshow == '0')
      ||
      !canedit
    )
      viewAttr = 1;

    return (
      <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@busup4`}
        viewAttr={viewAttr}
        value={text}
        onChange={e => this.onValueChange(e, paramName, record.id)}
      />
    );
  };
  inputRender(text, record, index, paramName) {
    let { auth: { canedit, canview } } = this.store;
    let viewAttr = 2
    if (!canedit) {
      viewAttr = 1
    }
    switch (paramName) {
      case 'customname':
        return <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@0p83ze`}
          value={text}
          viewAttr={viewAttr}
          onChange={e => this.onValueChange(e, paramName, record.id)}

        >

        </WeaInput>
      case 'showorder':
        return (
          <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@jazapb`}
            viewAttr={viewAttr}

            precision={2}
            value={text}
            onChange={e => this.onValueChange(e, paramName, record.id)}
          />
        );
      case 'showwidth':
        return (
          <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@v54p3s`}
            min={0}
            viewAttr={viewAttr}
            value={text}
            onChange={e => this.onValueChange(e, paramName, record.id)}
          />
        );
    }
  }

  onValueChange = (e, paramName, id) => {
    this.store.fieldRows[id][paramName] = e;
    if ("isshow" == paramName && e == '0') {
      this.store.fieldRows[id]['ismust'] = e;
    }
  };

  getDIYColumns = () => {
    return [
      {
        title: getLabel('33331', '字段'),
        dataIndex: 'showname',
        key: 'showname',
        width: '20%'
      },
      {
        title: this.getFieldNameColumn(getLabel('15603', '是否显示'), 'isshow'),
        dataIndex: 'isshow',
        key: 'isshow',
        width: '20%',
        render: (text, record, index) => {
          return this.checkBoxRender(text, record, index, 'isshow');
        },
      },
      {
        title: this.getFieldNameColumn(getLabel('25532', '是否必填'), 'ismust'),
        dataIndex: 'ismust',
        key: 'ismust',
        width: '20%',
        render: (text, record, index) => {
          return this.checkBoxRender(text, record, index, 'ismust');
        },
      },
      {
        title: getLabel('509086', '宽度比例') + "(%)",
        dataIndex: 'showwidth',
        key: 'showwidth',
        width: '20%',
        render: (text, record, index) => {
          return this.inputRender(text, record, index, 'showwidth');
        },
      },
      {
        title: getLabel('17607', '自定义名称'),
        dataIndex: 'customname',
        key: 'customname',
        width: '20%',
        render: (text, record, index) => {
          return this.inputRender(text, record, index, 'customname');
        },
      },
    ];
  };
  getPreviewTableConfig = () => {
    let totalWidth = 0
    this.store.fieldRows.map(v => {
      if (v.isshow == 1) {
        totalWidth += parseInt(v.showwidth)
      }
    })
    return {
      columns: this.getPreviewColumns(),
      scroll: { x: totalWidth + '%' }
    };
  };
  //       begindate2 enddate2 days2 result finishrate
  getDIYTableConfig = () => {
    let { auth: { canedit, canview } } = this.store;
    let dataSource = toJS(this.store.fieldRows)
    dataSource.sort((a, b) => {
      return a.showorder - b.showorder
    })
    return {
      columns: this.getDIYColumns(),
      dataSource,
      pagination: false,
      draggable: canedit ? true : false,
      onDrop: this.onDropEvent
    };
  };
  //拖拽排序
  onDropEvent = (data) => {
    data = data.map((d, i) => {
      d.id = i
      d.showorder = i
      return d
    })
    this.store.fieldRows = []
    this.store.fieldRows = data

  }
  sortShowOrder(a, b) {
    return parseInt(a) - parseInt(b)
  }

  onSearchGroupChange = (v) => {
    this.setState({ searchGroupVisible: v })
  }
  onSearchGroupPreviewChange = (v) => {
    this.setState({ searchGroupPreviewVisible: v })
  }
  onTitleClick = () => {
    this.setState({ searchGroupVisible: !this.state.searchGroupVisible })
  }
  onPreviewTitleClick = () => {
    this.setState({ searchGroupPreviewVisible: !this.state.searchGroupPreviewVisible })
  }
  cubeCallback = (param) => {
    if(param.type==1){//新建 
      this.store.setState("iscube","1")
      this.store.saveTemplateConfig()
    }else if (param.type==2){//删除
      //this.store.setState("iscube","0")
    }
  }
  render() {
    let { auth: { canedit, canview }, isshowsummary, setState, resourcetype, resourceid ,cubeResourceType,isopencube,iscube} = this.store;
    let {isShowCube} = this.state
    let viewAttr = canedit ? 2 : 1
    let EcmeSet = (window.weaCubeEngine && window.weaCubeEngine.com && window.weaCubeEngine.com.EcmeSet) || {};
    return (
      <div ref={this.saveRef}>
         <div>
        <div className="preview-table">
          <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@1s79wc`}
            className="diy-column"
            title={<div className="diy-title" onClick={this.onPreviewTitleClick}>{getLabel('509082', '工作总结预览')} </div>}
            showGroup={this.state.searchGroupPreviewVisible}
            onVisibleChange={this.onSearchGroupPreviewChange}
          >
            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@oty508`} {...this.getPreviewTableConfig()} />
          </WeaSearchGroup>
        </div>
        {(canview || canedit) &&
          <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@fz1jkd`}
            className="diy-column"
            title={<div className="diy-title" onClick={this.onTitleClick}>{getLabel('509088', '自定义总结列字段')}</div>}
            showGroup={this.state.searchGroupVisible}
            onVisibleChange={this.onSearchGroupChange}
          >
            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@qmijos`} {...this.getDIYTableConfig()} />
          </WeaSearchGroup>}
        </div>
        

       {/* {  iscube=='1' && this.state.hasLoad &&<EcmeSet query="workrelateplan" hideTop="1"  ispart="1" partType={cubeResourceType} partid={resourceid} callback={this.cubeCallback}/>} */}
      </div>
    );
  }
}
